package com.itmayiedu.JDBCutil.MyJDBC.Jdbcimpl;

import com.itmayiedu.JDBCutil.JDBCUtils;
import com.itmayiedu.JDBCutil.MyJDBC.Jdbcs;
import com.itmayiedu.annotation.ExtSelect;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Select implements Jdbcs {

    private Object[] args;
    private Method method;

    public Select(Method method, Object[] args) {
        this.args=args;
        this.method=method;
    }

    /**
     * 获得方法上的注解和参数注解和参数的值
     *  sql 和参数parameters
     *  再获得方法的返回参数类型
     * @param annotation
     * @return
     */
    @Override
    public Object Jdbcs(Annotation annotation) throws IllegalAccessException, InstantiationException, SQLException, NoSuchFieldException {
        ExtSelect extSelect=(ExtSelect) annotation;
        String SqlSelect = extSelect.value();
        Myparameters myparameters=new Myparameters(method,args);
        ConcurrentHashMap<Object, Object> Map = myparameters.getObjectObjectConcurrentHashMap();
        System.out.println("sql语句"+SqlSelect+"参数"+Map);
        /**
         * 利用反射，将jdbc查询到的结果集与object匹配
         */
        List params=MapToList(Map);
        ResultSet res= JDBCUtils.query(SqlSelect,params);
        if (!res.next()){
            return null;
        }
        //游标上移
        res.previous();
        Class<?> returnType = method.getReturnType();
        Object object = returnType.newInstance();
        while (res.next()){
            for (Object param:params){
                //通过参数获得返回对象的值
                Object resObject = res.getObject((String) param);
                //通过method的返回类型Class文件和参数名获得  属性设值方法
                Field field = returnType.getField((String) param);
                field.setAccessible(true);
                //给Object对象的param属性植入resObject值
                field.set(object,resObject);
            }
        }
        //最后返回object对象
        return object;
    }

    /**
     * 将map转换成为list
     * @param map
     * @return
     */
    private List MapToList(ConcurrentHashMap<Object, Object> map) {
        List params=new ArrayList();
        Iterator<Map.Entry<Object, Object>> it = map.entrySet().iterator();
        while (it.hasNext()){
            params.add(it.next().getValue());
        }
        return params;
    }
}
